import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiResponse } from '../dto/response.dto';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let message = '服务异常';

    if (exception instanceof HttpException) {
      status = exception.getStatus();
      const exceptionResponse = exception.getResponse();
      
      if (typeof exceptionResponse === 'object' && 'message' in exceptionResponse) {
        if (Array.isArray(exceptionResponse.message)) {
          message = exceptionResponse.message[0];
        } else {
          message = exceptionResponse.message as string;
        }
      } else {
        message = exception.message;
      }
    } else if (exception instanceof Error) {
      message = exception.message;
    }

    // 根据状态码返回对应的响应格式
    let apiResponse: ApiResponse;
    
    switch (status) {
      case HttpStatus.UNAUTHORIZED:
        apiResponse = ApiResponse.unauthorized(message);
        break;
      case HttpStatus.BAD_REQUEST:
        apiResponse = ApiResponse.badRequest(message);
        break;
      case HttpStatus.NOT_FOUND:
        apiResponse = ApiResponse.error(message, 404);
        break;
      case HttpStatus.CONFLICT:
        apiResponse = ApiResponse.error(message, 409);
        break;
      default:
        apiResponse = ApiResponse.error(message, status);
    }

    response.status(status).json(apiResponse);
  }
}
